package com.chaoxin.lovehelp.common.utils;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.InputStream;
import java.net.URI;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Random;

import com.aliyun.oss.model.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.multipart.MultipartFile;

import com.aliyun.oss.OSSClient;

/**
 * @author TengJay Huang
 * @version 1.0
 */

public class OSSClientUtil {
    /**
     * log日志
     */
    public static final Logger logger = LoggerFactory.getLogger(OSSClientUtil.class);
    /**
     * 访问域名
     */
//    @Value("${aliyun.oss.endpoint}")
    private String endpoint="oss-cn-shenzhen.aliyuncs.com";
    /**
     * accessKey访问秘钥
     *  访问用户
     */
//    @Value("${aliyun.oss.accessKeyId}")
    private String accessKeyId="LTAI5tLoV4uAy26ViMkasTqp";
    /**
     * 密钥
     */
//    @Value("${aliyun.oss.accessKeySecret}")
    private String accessKeySecret ="nCITjZ7hwLV9frpjt9CMXWgatvvxmY";
    /**
     * 空间  名称
     */
//    @Value("${aliyun.oss.bucketName}")
    private String bucketName="hope66";
    /**
     *  文件存储目录
     */
    private String filedir = "chaoxin/";

    private OSSClient ossClient;

    public OSSClientUtil() {

        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 初始化
     */
    public void init() {
        ossClient = new OSSClient(endpoint, accessKeyId, accessKeySecret);
    }

    /**
     * 销毁
     */
    public void destory() {

        ossClient.shutdown();
    }

    /**
     * 上传图片
     *
     * @param url
     * @throws
     */
    public void uploadImg2Oss(String url) throws IOException {
        File fileOnServer = new File(url);
        FileInputStream fin;
        try {
            fin = new FileInputStream(fileOnServer);
            String[] split = url.split("/");
            this.uploadFile2OSS(fin, split[split.length - 1]);
        } catch (FileNotFoundException e) {
            throw new IOException("图片上传失败");
        }
    }

    public String uploadImg2Oss(MultipartFile file) throws IOException {
        if (file.getSize() > 10 * 1024 * 1024) {
            throw new IOException("上传图片大小不能超过10M！");
        }
        String originalFilename = file.getOriginalFilename();
        String substring = originalFilename.substring(originalFilename.lastIndexOf(".")).toLowerCase();
        Random random = new Random();
        String name = random.nextInt(10000) + System.currentTimeMillis() + substring;
        try {
            InputStream inputStream = file.getInputStream();
            this.uploadFile2OSS(inputStream, name);
            return name;
        } catch (Exception e) {
            throw new IOException("图片上传失败");
        }
    }

    /**
     * 获得图片路径
     *
     * @param fileUrl
     * @return
     */
    public String getImgUrl(String fileUrl) {
        System.out.println(fileUrl);
        if (!StringUtils.isEmpty(fileUrl)) {
            String[] split = fileUrl.split("/");
            return this.getUrl(this.filedir + split[split.length - 1]);
        }
        return "" ;
    }

    /**
     * 上传到OSS服务器 如果同名文件会覆盖服务器上的
     *
     * @param instream
     *            文件流
     * @param fileName
     *            文件名称 包括后缀名
     * @return 出错返回"" ,唯一MD5数字签名
     */
    public String uploadFile2OSS(InputStream instream, String fileName) {

        String ret = "";
        try {
            // 创建上传Object的Metadata
            ObjectMetadata objectMetadata = new ObjectMetadata();
            objectMetadata.setContentLength(instream.available());
            objectMetadata.setCacheControl("no-cache");
            objectMetadata.setHeader("Pragma", "no-cache");
            objectMetadata.setContentType(getcontentType(fileName.substring(fileName.lastIndexOf("."))));
            objectMetadata.setContentDisposition("inline;filename=" + fileName);
            // 上传文件
            PutObjectResult putResult = ossClient.putObject(bucketName, filedir + fileName, instream, objectMetadata);
            ret = putResult.getETag();
        } catch (IOException e) {
            logger.error(e.getMessage(), e);
        } finally {
            try {
                if (instream !=null ) {
                    instream.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return ret;
    }

    /**
     * Description: 判断OSS服务文件上传时文件的contentType
     *
     * @param
     *
     * @return String
     */
    public static String getcontentType(String filenameExtension) {
        if (filenameExtension.equalsIgnoreCase("bmp")) {
            return "image/bmp";
        }
        if (filenameExtension.equalsIgnoreCase("gif")) {
            return "image/gif";
        }
        if (filenameExtension.equalsIgnoreCase("jpeg") || filenameExtension.equalsIgnoreCase("jpg")
                || filenameExtension.equalsIgnoreCase("png")) {
            return "image/jpeg";
        }
        if (filenameExtension.equalsIgnoreCase("html")) {
            return "text/html";
        }
        if (filenameExtension.equalsIgnoreCase("txt")) {
            return "text/plain";
        }
        if (filenameExtension.equalsIgnoreCase("vsd")) {
            return "application/vnd.visio";
        }
        if (filenameExtension.equalsIgnoreCase("pptx") || filenameExtension.equalsIgnoreCase("ppt")) {
            return "application/vnd.ms-powerpoint";
        }
        if (filenameExtension.equalsIgnoreCase("docx") || filenameExtension.equalsIgnoreCase("doc")) {
            return "application/msword";
        }
        if (filenameExtension.equalsIgnoreCase("xml")) {
            return "text/xml";
        }
        return "image/jpeg";
    }

    /**
     * 获得url链接
     *
     * @param key
     * @return
     */
    public String getUrl(String key) {
        // 设置URL过期时间为80年 3600l* 1000*24*365*10*8

        Date expiration = new Date(System.currentTimeMillis() + 3600L * 1000 * 24 * 365 * 10*8);
        // 生成URL
        // URL url = ossClient.generatePresignedUrl(bucketName, key, expiration);
        String url = "https://"+bucketName+"."+endpoint+"/"+key;
        if (url != null) {
            return url.toString();
        }
        return  "";
    }

    /**
     * 删除OSS上的文件
     * @param fileName 文件名，包含存储目录
     */
    public void deleteFileFromOSS(String fileName) {
        try {
            // 拼接完整的文件路径
            String fullKey = filedir + fileName;
            // 删除文件
            ossClient.deleteObject(bucketName,  fullKey);
            logger.info(" 文件 {} 从OSS删除成功", fullKey);
        } catch (Exception e) {
            logger.error(" 文件删除失败: {}", e.getMessage(),  e);
        }
    }
    /**
     * 获取指定目录下的所有文件名
     * @param directory 目录名
     * @return 文件名列表
     */
    public List<String> getFileNamesInDirectory(String directory) {
        List<String> fileNames = new ArrayList<>();
        // 确保目录以斜杠结尾
        if (!directory.endsWith("/")) {
            directory = directory + "/";
        }
        ListObjectsRequest listObjectsRequest = new ListObjectsRequest(bucketName);
        listObjectsRequest.setPrefix(directory);
        ObjectListing objectListing = ossClient.listObjects(listObjectsRequest);
        for (OSSObjectSummary objectSummary : objectListing.getObjectSummaries()) {
            String key = objectSummary.getKey();
            // 排除目录本身
            if (!key.equals(directory)) {
                // 提取文件名
                String fileName = key.substring(key.lastIndexOf("/") + 1);
                fileNames.add(fileName);
            }
        }
        return fileNames;
    }

    public static void main(String[] args) {
        OSSClientUtil ossClientUtil = new OSSClientUtil();
        List<String> fileNames = ossClientUtil.getFileNamesInDirectory("chaoxin");
        System.out.println(fileNames);
    }

}
